package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysUserInfo;
import com.itheima.ydd.entity.SysConfig;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.ISysConfigService;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.ISysUserService;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/sys_user")
@Slf4j
@CrossOrigin
public class SysUserController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;

    @GetMapping("/list")
    public R list(String login_name, Integer status, String phone, int page, int limit) {
        //创建分页构造器,查询系统用户信息
        Page<SysUser> pageInfo = new Page<>(page, limit);
        Page<SysUserInfo> userInfoPage = new Page<>();

        //创建条件构造构造器
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(login_name != null, SysUser::getLoginName, login_name);
        queryWrapper.like(phone != null, SysUser::getPhone, phone);
        queryWrapper.eq(status != null, SysUser::getStatus, status);

        //分页查询
        userService.page(pageInfo, queryWrapper);
        //Copy
        BeanUtils.copyProperties(pageInfo, userInfoPage, "records");
        //遍历集合,添加元素
        List<SysUser> records = pageInfo.getRecords();

        List<SysUserInfo> collect = records.stream().map(item -> {
            SysUserInfo sysUserInfo = new SysUserInfo();
            BeanUtils.copyProperties(item, sysUserInfo);

            log.info(item.getRoleId());
            //获取角色ID,添加角色信息
            //查询用户角色id集合: role_id
            String[] rowIds = item.getRoleId().replace("[", "")
                    .replace("]", "")
                    .replace("\"", "")
                    .split(",");
            List<String> ids = new ArrayList<>();
            Collections.addAll(ids, rowIds);
            List<SysRole> roles = roleService.listByIds(ids);
            List<String> strings = roles.stream().map(getRoleName -> {
                String s = getRoleName.getName();
                return s;
            }).collect(Collectors.toList());
            sysUserInfo.setRole_id(ids);
            sysUserInfo.setRolename(strings);
            sysUserInfo.setCreate_date(item.getCreateDate());
            sysUserInfo.setLogin_name(item.getLoginName());
            return sysUserInfo;
        }).collect(Collectors.toList());

        userInfoPage.setRecords(collect);
        // List<SysUserInfo> data = userInfoPage.getRecords();

        R r = new R();
        r.putData("count",userInfoPage.getTotal());
        r.putData("totalPages", userInfoPage.getPages());
        r.putData("pageSize", userInfoPage.getSize());
        r.putData("currentPage", userInfoPage.getCurrent());
        r.putData("data", userInfoPage.getRecords());



        r.setErrno(0);
        r.setErrmsg("");
        return r;
        //return R.success("", userInfoPage );
    }


    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {
        SysUser user = userService.getById(id);

        //查询用户角色id集合: role_id
        String[] rowIds = user.getRoleId().replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        List<String> ids = new ArrayList<>();
        Collections.addAll(ids, rowIds);

        SysUserInfo userInfo = new SysUserInfo();
        BeanUtils.copyProperties(user, userInfo);
        userInfo.setRole_id(ids);

        return ResultData.ok("", userInfo);

    }

    @PostMapping("/update")
    public ResultData update(@RequestBody SysUserInfo sysUserInfo) {
        log.info("接收到的参数:{}", sysUserInfo);
        System.out.println(sysUserInfo);
        //获取角色ID字符串
        List<String> role_id = sysUserInfo.getRole_id();
        if (role_id != null) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("[");
            for (int i = 0; i < role_id.size(); i++) {
                if (i == (role_id.size() - 1)) {
                    stringBuffer.append("\"" + role_id.get(i) + "\"");
                } else {
                    stringBuffer.append("\"" + role_id.get(i) + "\"" + ",");
                }
            }
            stringBuffer.append("]");
            String toString = stringBuffer.toString();


            log.info("参数:{}", toString);
            System.out.println(toString);
            //封装数据
            SysUser user = new SysUser();
            user.setId(sysUserInfo.getId());
            user.setLoginName(sysUserInfo.getLogin_name());
            user.setPassword(sysUserInfo.getPassword());
            user.setName(sysUserInfo.getName());
            user.setEmail(sysUserInfo.getEmail());
            user.setPhone(sysUserInfo.getPhone());
            user.setLoginIp(sysUserInfo.getLogin_ip());
            user.setCreateDate(sysUserInfo.getCreate_date());
            user.setUpdateDate(sysUserInfo.getUpdate_date());
            user.setDelFlag(sysUserInfo.getDel_flag());
            user.setRoleId(toString);
            user.setStatus(sysUserInfo.getStatus());
            user.setDefaultData(sysUserInfo.getDefault_data());

            //修改数据
            userService.updateById(user);

            //  userService.updateById(user);
            return ResultData.ok("修改成功", null);
        }else {
            LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SysUser::getId,sysUserInfo.getId());
            updateWrapper.set(SysUser::getStatus,sysUserInfo.getStatus());
            userService.update(updateWrapper);
            return ResultData.ok("修改成功", null);
        }
    }

   @PostMapping("/add")
    public ResultData add(@RequestBody SysUserInfo sysUserInfo) {
        //获取角色ID字符串
       sysUserInfo.getId();
        List<String> role_id = sysUserInfo.getRole_id();

        StringBuffer stringBuffer = new StringBuffer();

        stringBuffer.append("[");
        for (int i = 0; i < role_id.size(); i++) {
            if (i == (role_id.size() - 1)) {
                stringBuffer.append("\"" + role_id.get(i) + "\"");
            } else {
                stringBuffer.append("\"" + role_id.get(i) + "\"" + ",");
            }
        }
        stringBuffer.append("]");
        String toString = stringBuffer.toString();


        log.info("参数:{}", toString);
        System.out.println(toString);
        //封装数据
        SysUser user = new SysUser();
        user.setId(sysUserInfo.getId());
        user.setLoginName(sysUserInfo.getLogin_name());
        user.setPassword(sysUserInfo.getPassword());
        user.setName(sysUserInfo.getName());
        user.setEmail(sysUserInfo.getEmail());
        user.setPhone(sysUserInfo.getPhone());
        user.setLoginIp(sysUserInfo.getLogin_ip());
        user.setCreateDate(LocalDateTime.now());
        user.setUpdateDate(LocalDateTime.now());
        user.setDelFlag(sysUserInfo.getDel_flag());
        user.setRoleId(toString);
        user.setStatus(sysUserInfo.getStatus());
        user.setDefaultData(sysUserInfo.getDefault_data());

        //添加数据
        userService.save(user);

        //  userService.updateById(user);
        return ResultData.ok("添加成功", null);
    }

    @GetMapping("/del")
    public ResultData del(String id){
        userService.removeById(id);
        return ResultData.ok("删除成功",null);
    }

}
